package com.supermarket.manage.buiness.handler;

import com.alibaba.fastjson.JSON;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限验证异常拦截器
 *
 * @author: Faxon
 * @data: 2020/2/22
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            response.getWriter().write(
                    JSON.toJSONString(
                            new ResponseResult<>(CodeStatus.INSUFFICIENT_PERMISSIONS, "权限不足，请联系管理员")
                    )
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
